﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Transformable_Engine_v2.Engine.Input;

namespace Project_Maverick.Controller.Input
{
    public class PlayerInput
    {
        public enum Action
        {
            Accept,
            Cancel,
            Up,
            Down,
            Left,
            Right
        }

        public Dictionary<KeyboardInput.Key, Action> Actions { get; private set; }

        public PlayerInput()
        {
            Actions = new Dictionary<KeyboardInput.Key, Action>();
        }

        public void Save(string filePath)
        {
            XDocument input = new XDocument(
                new XElement("Input",
                        new XElement("AcceptKey", Actions.First(a => a.Value == Action.Accept).Key),
                        new XElement("CancelKey", Actions.First(a => a.Value == Action.Cancel).Key),
                        new XElement("UpKey", Actions.First(a => a.Value == Action.Up).Key),
                        new XElement("DownKey", Actions.First(a => a.Value == Action.Down).Key),
                        new XElement("LeftKey", Actions.First(a => a.Value == Action.Left).Key),
                        new XElement("RightKey", Actions.First(a => a.Value == Action.Right).Key))
                );
            input.Save(filePath);
        }

        public static PlayerInput FromFile(string filePath)
        {
            XDocument input = XDocument.Load(filePath);
            
            PlayerInput p = new PlayerInput();
            p.Actions.Add(ParseValue(input.Descendants("AcceptKey").First().Value), Action.Accept);
            p.Actions.Add(ParseValue(input.Descendants("CancelKey").First().Value), Action.Cancel);
            p.Actions.Add(ParseValue(input.Descendants("UpKey").First().Value), Action.Up);
            p.Actions.Add(ParseValue(input.Descendants("LeftKey").First().Value), Action.Left);
            p.Actions.Add(ParseValue(input.Descendants("DownKey").First().Value), Action.Down);
            p.Actions.Add(ParseValue(input.Descendants("RightKey").First().Value), Action.Right);

            return p;
        }

        static KeyboardInput.Key ParseValue(string key)
        {
            return (KeyboardInput.Key) Enum.Parse(typeof (KeyboardInput.Key), key);
        }
    }
}